package com.jeesite.modules.app.mockexam.special.single.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.modules.conf.RedisUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.cache.JedisUtils;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.modules.app.mockexam.special.record.entity.AppMockexamSpecialRecord;
import com.jeesite.modules.app.mockexam.special.record.service.AppMockexamSpecialRecordService;
import com.jeesite.modules.app.mockexam.special.user.entity.TmockexamSpecialUser;
import com.jeesite.modules.app.mockexam.special.user.service.TmockexamSpecialUserService;
import com.jeesite.modules.app.mockexam.theory.entity.AppExaminateTheory;
import com.jeesite.modules.app.mockexam.theory.record.entity.AppMockexamTheoryRecord;
import com.jeesite.modules.app.util.answer.AnswerUtils;
import com.jeesite.modules.conf.AppController;
import com.jeesite.modules.conf.MessageCode;
import com.jeesite.modules.zx.customer.exercises.entity.TcustomerExercises;
import com.jeesite.modules.zx.mockexam.special.single.entity.TmockexamSpecialSingle;
import com.jeesite.modules.zx.mockexam.special.single.service.TmockexamSpecialSingleService;
import com.jeesite.modules.zx.question.bank.entity.TquestionBank;
import com.jeesite.modules.zx.question.bank.service.TquestionBankService;

@Controller
@RequestMapping(value = "/app/mockexam/special/single/")
public class AppMockexamSpecialSingleController {
	@Autowired
	private TmockexamSpecialSingleService tmockexamSpecialSingleService;
	@Autowired
	private AppMockexamSpecialRecordService appMockexamSpecialRecordService;
	@Autowired
	private TmockexamSpecialUserService tmockexamSpecialUserService;
	@Autowired
	private TquestionBankService tquestionBankService;

	@Autowired
	private RedisUtils redisUtils;

	@RequestMapping(value = "subjectRecordList")
	public void subjectRecordList(TmockexamSpecialSingle entity, Model model,HttpServletRequest request,HttpServletResponse response) {
		List<TmockexamSpecialSingle> subjList = tmockexamSpecialSingleService.findList(entity);
		String theoryId=request.getParameter("theoryId");
		if(StringUtils.isBlank(theoryId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "练习标识");
			return;
		}
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		List<String> subidList=new ArrayList<>();
		for(TmockexamSpecialSingle subject:subjList){
			String objName = subject.getObjName();
			subidList.add(objName);
		}			
				
		if(subidList.size()>0){
			TquestionBank quebank=new TquestionBank();
			quebank.getSqlMap().getWhere().and("id", QueryType.IN, subidList);
			List<TquestionBank> quetbankList = tquestionBankService.findList(quebank);
			for(TquestionBank question:quetbankList){
				String id = question.getId();
				AppMockexamSpecialRecord theoryRecord=new AppMockexamSpecialRecord();
				theoryRecord.setSpecialId(theoryId);
				theoryRecord.setPostId(entity.getParentCode());
				theoryRecord.setUserId(userId);
				theoryRecord.setQuestionId(id);
				theoryRecord.setType("single");
				List<AppMockexamSpecialRecord> findList = appMockexamSpecialRecordService.findList(theoryRecord);
				if(findList.size()>0){
					AppMockexamSpecialRecord arecord = findList.get(0);
					String answerId = arecord.getAnswerId();
					BigDecimal score = arecord.getScore();
					question.setAnswer(answerId);
					question.setScore(score.doubleValue());
					if(StringUtils.isNotBlank(answerId)){
						String[] split = answerId.split(",");
						for(String key:split){
						    if(key.equals("1")){
						    	question.setAnswer1("1");
						    }
						    if(key.equals("2")){
						    	question.setAnswer2("2");
						    }
						    if(key.equals("3")){
						    	question.setAnswer3("3");
						    }
						    if(key.equals("4")){
						    	question.setAnswer4("4");
						    }
						    if(key.equals("5")){
						    	question.setAnswer5("5");
						    }
						}
					}
				}
			}
			JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(quetbankList));
			AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
			return;
		  }
		JSONArray parseArray = new JSONArray();
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
		
	}
	@RequestMapping(value="optionList")
	public void optionList(TmockexamSpecialSingle entity, HttpServletRequest request,HttpServletResponse response){
		AppMockexamSpecialRecord appMockexamSpecialRecord=new AppMockexamSpecialRecord();
		appMockexamSpecialRecord.setType("single");
		String specialId=request.getParameter("specialId");
		if(StringUtils.isBlank(specialId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "查询标识");
			return;
		}
		appMockexamSpecialRecord.setSpecialId(specialId);
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		appMockexamSpecialRecord.setUserId(userId);
		String questionId=request.getParameter("questionId");
		if(StringUtils.isBlank(questionId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "问题标识");
			return;
		}
		appMockexamSpecialRecord.setQuestionId(questionId);
		List<AppMockexamSpecialRecord> recordList = appMockexamSpecialRecordService.findList(appMockexamSpecialRecord);
		List<String> list=new ArrayList<>();
		for(AppMockexamSpecialRecord recor:recordList){
			String answerId = recor.getAnswerId();
			for(String key:answerId.split(",")){
				list.add(key);
			}
		}
		List<TmockexamSpecialSingle> findList = tmockexamSpecialSingleService.findList(entity);
		for(TmockexamSpecialSingle single:findList){
			String id = single.getId();
			if(list.contains(id)){
				single.setChecked(true);
			}
		}
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	@PostMapping(value = "saveRecord")
	public void saveRecord(AppMockexamSpecialRecord entity,HttpServletRequest request,HttpServletResponse response) {
//		 String specialId=entity.getSpecialId();		// 专项练习标识
//		 if(StringUtils.isBlank(specialId)){
//			 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "主题标识");
//			 return;
//		 }
//		 String type=entity.getType();		// 类型
//         if(StringUtils.isBlank(type)){
//        	 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "类型");
//			 return;
//		 }
         String userId=entity.getUserId();		// 用户主键
         if(StringUtils.isBlank(userId)){
        	 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			 return;
		 }
		 String answerId=entity.getAnswerId();		// 答案字段
         if(StringUtils.isBlank(answerId)){
        	 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "答案信息");
			 return;
		 }
         String postId=entity.getPostId();
         if(StringUtils.isBlank(postId)){
        	 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "知识类型");
			 return;
         }
         String questionId=entity.getQuestionId();		// 问题id
		 if(StringUtils.isBlank(questionId)){
        	 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "问题标识");
			 return;
		 }

		TquestionBank answerObj = null;
		String questionIdKey = postId+"-"+questionId;
		if (redisUtils.hasKey(questionIdKey)){
			answerObj = (TquestionBank) redisUtils.get(questionIdKey);
		}else{
			answerObj = tquestionBankService.get(questionId);
			redisUtils.set(questionIdKey,answerObj);
		}
		if(answerObj==null){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "问题数据不存在");
			return;
		}
		String objAnswer = answerObj.getObjAnswer();

		//当前用户当前题的记录
		AppMockexamSpecialRecord mockexamSpecialRecord = null;
		String currentKey = userId+"-"+postId+"-"+questionId;
		String id="";
		if (redisUtils.hasKey(currentKey)){
			mockexamSpecialRecord = (AppMockexamSpecialRecord) redisUtils.get(currentKey);
		}else{
			AppMockexamSpecialRecord asrmodel=new AppMockexamSpecialRecord();
//         asrmodel.setSpecialId(specialId);
//         asrmodel.setType(type);
			asrmodel.setUserId(userId);
			asrmodel.setPostId(postId);
			asrmodel.setQuestionId(questionId);
			mockexamSpecialRecord = appMockexamSpecialRecordService.get(asrmodel);
			if(mockexamSpecialRecord!=null){
				redisUtils.set(currentKey,mockexamSpecialRecord);
			}
		}
		if(mockexamSpecialRecord!=null){
			id = mockexamSpecialRecord.getId();
		}
   		 //answerId:1,3,4,2
   		 //objAnswer:1,2,3,4
   		if(StringUtils.isNotBlank(objAnswer)) {
   			//先判断长度
   			boolean sco=AnswerUtils.calculation(objAnswer, answerId);
		    if(sco) {
				Double score = answerObj.getScore();
			    entity.setScore(new BigDecimal(score));
			}else {
				entity.setScore(new BigDecimal(0.0));
			}
   		}
   		 if(StringUtils.isNotBlank(id)){
   			entity.setId(id);
   			appMockexamSpecialRecordService.update(entity);
   		 }else{
		    appMockexamSpecialRecordService.save(entity);
   		 }
   		 JSONObject obj=JSONObject.parseObject(JsonMapper.toJson(entity));
   		if(StringUtils.isNotBlank(userId)) {
    		//查询错误数
    		AppMockexamSpecialRecord record=new AppMockexamSpecialRecord();
    		record.setUserId(userId);
    		record.setPostId(postId);
    		record.setScore(new BigDecimal(0.0));
			long error = appMockexamSpecialRecordService.findCount(record);
			obj.put("error", error);
			//正确数
			AppMockexamSpecialRecord recordSucc=new AppMockexamSpecialRecord();
			recordSucc.setUserId(userId);
			recordSucc.setPostId(postId);
			recordSucc.getSqlMap().getWhere().and("score", QueryType.GT, 0);
			long success = appMockexamSpecialRecordService.findCount(recordSucc);
			obj.put("success", success);
    	}
   		 AppController.renderSuccessObject(response, obj, MessageCode.SUCCESS_ACK);
	}
	/**
	 * 保存专项练习记录
	 */
	@PostMapping(value = "save")
	public void save(AppMockexamSpecialRecord entity,HttpServletRequest request,HttpServletResponse response) {
		 String specialId=entity.getSpecialId();		// 专项练习标识
		 if(StringUtils.isBlank(specialId)){
			 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "主题标识");
			 return;
		 }
		 String type=entity.getType();		// 类型
         if(StringUtils.isBlank(type)){
        	 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "类型");
			 return;
		 }
		 String userId=entity.getUserId();		// 用户主键
         if(StringUtils.isBlank(userId)){
        	 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			 return;
		 }
		 String answerId=entity.getAnswerId();		// 答案字段
         if(StringUtils.isBlank(answerId)){
        	 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "答案信息");
			 return;
		 }
		 Integer questionType=entity.getQuestionType();		// 问题类型
		 String questionId=entity.getQuestionId();		// 问题id
		 if(StringUtils.isBlank(questionId)){
        	 AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "问题标识");
			 return;
		 }
		 AppMockexamSpecialRecord asrmodel=new AppMockexamSpecialRecord();
         asrmodel.setSpecialId(specialId);
         asrmodel.setType(type);
         asrmodel.setUserId(userId);
         asrmodel.setQuestionId(questionId);
         List<AppMockexamSpecialRecord> findList = appMockexamSpecialRecordService.findList(asrmodel);
         String id="";
         if(findList!=null&&findList.size()>0){
        	 id=findList.get(0).getId();
         }
		 //查询问题的答案
		 TmockexamSpecialSingle tss=new TmockexamSpecialSingle();
		 tss.setParentCode(questionId);
		 tss.setObjAnswer("1");
		 TmockexamSpecialSingle  answerObj = tmockexamSpecialSingleService.get(answerId);
   		 String objAnswer = answerObj.getObjAnswer();
   		 if(StringUtils.isNotBlank(objAnswer)&&objAnswer.equals("1")){
   			TmockexamSpecialSingle question = tmockexamSpecialSingleService.get(questionId);
			 Double score = question.getScore();
			 entity.setScore(new BigDecimal(score));
   		 }else{
   			 entity.setScore(new BigDecimal(0.0));
   		 }
   		 if(StringUtils.isNotBlank(id)){
   			entity.setId(id);
   			appMockexamSpecialRecordService.update(entity);
   		 }else{
		    appMockexamSpecialRecordService.save(entity);
   		 }
	}
	@RequestMapping(value="findPage")
	public void findPage(TmockexamSpecialSingle entity, HttpServletRequest request,HttpServletResponse response){
		entity.setParentCode("0");
		entity.setPage(new Page<>(request, response));
		Page<TmockexamSpecialSingle> findPage = tmockexamSpecialSingleService.findPage(entity);
		JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(findPage));
		AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
	}
	@RequestMapping(value="findList")
	public void findList(TmockexamSpecialSingle entity, HttpServletRequest request,HttpServletResponse response){
		List<TmockexamSpecialSingle> findList = tmockexamSpecialSingleService.findList(entity);
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	@RequestMapping(value="listQuestion")
	public void listQuestion(TmockexamSpecialSingle entity, HttpServletRequest request,HttpServletResponse response){
		List<TmockexamSpecialSingle> findList = tmockexamSpecialSingleService.findList(entity);
		List<String> questionIds=new ArrayList<>();
		for(TmockexamSpecialSingle single:findList){
			String objName = single.getObjName();
			questionIds.add(objName);
		}
		if(questionIds.size()>0){
			TquestionBank qustion=new TquestionBank();
			qustion.getSqlMap().getWhere().and("id", QueryType.IN, questionIds);
			List<TquestionBank> findList2 = tquestionBankService.findList(qustion);
			JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList2));
			AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
			return;
		}else{
			AppController.renderSuccessObject(response, "", MessageCode.SUCCESS_ACK);
		}
		
	}
	@RequestMapping(value="questionList")
	public void questionList(TmockexamSpecialSingle entity, HttpServletRequest request,HttpServletResponse response){
		AppMockexamSpecialRecord appMockexamSpecialRecord=new AppMockexamSpecialRecord();
		appMockexamSpecialRecord.setType("single");
		String specialId=request.getParameter("specialId");
		if(StringUtils.isBlank(specialId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "查询标识");
			return;
		}
		appMockexamSpecialRecord.setSpecialId(specialId);
		String userId=request.getParameter("userId");
		if(StringUtils.isBlank(userId)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
			return;
		}
		appMockexamSpecialRecord.setUserId(userId);		
		List<TmockexamSpecialSingle> findList = tmockexamSpecialSingleService.findList(entity);
		for(TmockexamSpecialSingle single:findList){
			String id = single.getId();			
			appMockexamSpecialRecord.setQuestionId(id);
			List<AppMockexamSpecialRecord> recordList = appMockexamSpecialRecordService.findList(appMockexamSpecialRecord);
			for(AppMockexamSpecialRecord recor:recordList){
				BigDecimal score = recor.getScore();
				single.setScore(score.doubleValue());
			}
		}
		JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
		AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
	}
	@RequestMapping(value="init")
	public void init(TmockexamSpecialSingle entity,HttpServletRequest request,HttpServletResponse response){
		entity.setPage(new Page<>(request, response));
		Page<TmockexamSpecialSingle> findPage = tmockexamSpecialSingleService.findPage(entity);
		JSONObject parseObject = JSONObject.parseObject(JsonMapper.toJson(findPage));
		AppController.renderSuccessObject(response, parseObject, MessageCode.SUCCESS_ACK);
	}
	@RequestMapping(value="detail")
	public void detail(TmockexamSpecialSingle entity,HttpServletRequest request,HttpServletResponse response){
		String id = entity.getId();
		if(StringUtils.isBlank(id)){
			AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "主键不存在");
			return;
		}
		tmockexamSpecialSingleService.get(id);
	}
}
